//  this library.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/dao/login_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/login/login_type_enum.dart';
import 'package:hktk_app/ienum/login/suc_return_enum.dart';
import 'package:hktk_app/model/login/config_model.dart';
import 'package:hktk_app/pages/login/reset_password_page.dart';
import 'package:hktk_app/util/font_util.dart';

// import 'package:hktk_app/util/navigator_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/back_button_widget.dart';
import 'package:hktk_app/widget/login/phone_agreement_widget.dart';
import 'package:hktk_app/widget/login/phone_input_widget.dart';

/// 手机号登录页面
class PhonePage extends StatefulWidget {
  /// 协议相关url
  final AppConfig appConfig;

  /// 右上角关闭按钮是否是游客模式按钮，是的话直接跳转首页
  final bool closeVisitors;

  /// 返回按钮是否显示
  final bool showBack;

  /// 跳转对应页面
  final Widget? onPage;
  final String pageName;

  /// 返回方式
  final SucReturnEnum sucReturn;

  const PhonePage({
    super.key,
    required this.appConfig,
    required this.closeVisitors,
    required this.sucReturn,
    this.showBack = true,
    this.onPage,
    this.pageName = "/tab",
  });

  @override
  State<PhonePage> createState() => _PhonePageState();
}

class _PhonePageState extends State<PhonePage> {
  /// 输入框页面对应的下标
  int _inputIndex = 0;

  /// 是否同意协议
  late bool _isSelect;

  /// 手机号输入框控制器
  final TextEditingController _phoneController = TextEditingController();

  /// 验证码输入框控制器
  final TextEditingController _captchaController = TextEditingController();

  /// 密码输入框控制器
  final TextEditingController _passwordController = TextEditingController();

  /// 页面滑动控制器
  late PageController _pageController;

  /// 上下文控制器
  late BuildContext _context;

  /// 验证手机号是否正确的方法
  final RegExp exp = RegExp(
      '^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$');
  late OverlayEntry? loadingEntry=null ;
  /// 背景
  get _background => Image.asset(
        "images/login/login_background.png",
        width: 1.sw,
        height: 450,
        fit: BoxFit.fill,
      );

  /// 登录模式切换
  get _mode => Container(
        padding: EdgeInsets.symmetric(horizontal: 20),
        height: 35,
        child: Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _modeShow("验证码登录", 0),
            hiSpace(width: 20),
            _split,
            hiSpace(width: 20),
            _modeShow("密码登录", 1),
          ],
        ),
      );

  /// 竖向分割线
  get _split => Container(
        height: 32,
        margin: EdgeInsets.only(top: 5),
        decoration: BoxDecoration(
          border: Border(
            left: BorderSide(color: colorBlack5, width: 2),
          ),
        ),
      );

  /// 输入框
  get _input => SizedBox(
        height: 255,
        child: PageView(
          //当页面选中后回调此方法
          //参数[index]是当前滑动到的页面角标索引 从0开始
          onPageChanged: (index) {
            setState(() {
              _inputIndex = index;
            });
          },
          //横向滑动切换
          scrollDirection: Axis.horizontal,
          //页面控制器
          controller: _pageController,
          //所有的子Widget
          children: [
            _inputPage(
              widget: PhoneInputWidget.captcha(
                controller: _captchaController,
                rightOnTapFun: _sendCaptcha,
              ),
              isPhone: false,
            ),
            _inputPage(
              widget: PhoneInputWidget.password(
                controller: _passwordController,
              ),
              isPhone: true,
            ),
          ],
        ),
      );

  /// 是否选中
  get _tipsSelected => GestureDetector(
        onTap: () {
          setState(() {
            _isSelect = !_isSelect;
          });
        },
        child: Container(
          margin: EdgeInsets.only(top: 6),
          child: _isSelect ? _selected : _unchecked,
        ),
      );

  /// 选中样式
  get _selected => SvgPicture.asset(
        "images/login/authority_select.svg",
        width: 18,
        height: 18,
      );

  /// 未选中样式
  get _unchecked => Container(
        width: 18,
        height: 18,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(9)),
            border: Border.all(
              color: colorBlack5,
            )),
      );

  @override
  void initState() {
    super.initState();
    _pageController = PageController(
      ///用来配置PageView中默认显示的页面 从0开始
      initialPage: 0,

      ///为true是保持加载的每个页面的状态
      keepPage: true,
    );
    _isSelect = false;
  }

  @override
  void dispose() {
    super.dispose();
    _phoneController.dispose();
    _captchaController.dispose();
    _passwordController.dispose();
    _pageController.dispose();
    loadingEntry?.remove();
    loadingEntry=null;
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    // 获取页面宽高
    // var of = MediaQuery.of(context);
    double width = ScreenUtil().screenWidth;
    double height = ScreenUtil().screenHeight;
    // double bottom = of.padding.bottom;
    return Scaffold(
      backgroundColor: colorWhite2,
      body: SizedBox(
        width: width,
        height: height,
        child: SingleChildScrollView(
          child: SizedBox(
            width: width,
            height: height,
            child: Stack(
              children: [
                _background,
                _content(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 页面内容
  _content() {
    return Column(
      children: [
        _titleWidget(),
        Expanded(
          child: MediaQuery.removePadding(
            context: _context,
            removeTop: true,
            child: ListView(
              children: [
                hiSpace(height: 44),
                _loginInput(),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 标题
  _titleWidget() {
    // 获取安全边距
    var top = ScreenUtil().statusBarHeight;
    return Container(
      height: 88,
      margin: EdgeInsets.only(top: top),
      padding: EdgeInsets.symmetric(horizontal: 18),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          widget.showBack
              ? BackButtonWidget.close(
                  pageContext: _context,
                  size: 20,
                  onTapFun: () {
                    if(Navigator.canPop(context)){
                      Navigator.maybePop(context);
                    }else{
                      SystemNavigator.pop();
                    }
                  })
              : SizedBox(
                  height: 20,
                  width: 48,
                ),
          Text(
            "手机号登录",
            style: FontUtil.fontBlack1(24, fontWeight: FontWeight.w500),
          ),
          // 右边占位使用
          !widget.showBack
              ? BackButtonWidget.close(
                  pageContext: _context,
                  onTapFun: _tourists,
                )
              : SizedBox(
                  height: 48,
                  width: 48,
                ),
        ],
      ),
    );
  }

  /// 登录输入方法
  _loginInput() {
    return Column(
      children: [
        _mode,
        hiSpace(height: 56),
        _input,
        hiSpace(height: 20),
        // // 切换一键登录按钮
        // GestureDetector(
        //   onTap: () {
        //
        //   },
        //   child: Icon(Icons.phone_android,size: 40,color: Colors.blue,),
        // )
        // ,
        Container(
          margin: EdgeInsets.symmetric(horizontal: 10),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              _tipsSelected,
              hiSpace(width: 10),
              Expanded(
                child: PhoneAgreementWidget(
                  appConfig: widget.appConfig,
                ),
              )
            ],
          ),
        ),
        hiSpace(height: 10),
        _loginButton(),
        _tourLoginButton()
      ],
    );
  }

  /// 登录模式显示
  _modeShow(String title, int index) {
    return GestureDetector(
      onTap: () {
        if (_inputIndex != index) {
          _pageController.animateToPage(index,
              duration: const Duration(milliseconds: 300), curve: Curves.ease);
          setState(() {
            _inputIndex = index;
          });
        }
      },
      child: Text(title,
          style: _inputIndex == index
              ? FontUtil.fontBlack1(20, fontWeight: FontWeight.w500)
              : FontUtil.fontGrey1(20)),
    );
  }

  /// 发送验证码方法
  Future<bool> _sendCaptcha() async {
    // 获取输入手机号
    String text = _phoneController.text;
    if (!exp.hasMatch(text)) {
      ToastUtil.show(context: _context, msg: "请输入正确的手机号");
      return false;
    }

    // 发送验证码方法
    bool res;
    try {
      await LoginDao.phoneCode(phone: text);
      res = true;
    } catch (e) {
      res = false;
      String msg = "未知错误，请重试";
      if (e is DaoException) {
        msg = e.msg;
      }
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        ToastUtil.show(context: _context, msg: msg);
      });
    }
    return res;
  }

  /// 输入框页面显示
  _inputPage({required Widget widget, required bool isPhone}) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 54),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          PhoneInputWidget.phone(controller: _phoneController),
          hiSpace(height: 40),
          widget,
          hiSpace(height: 20),
          if (isPhone) _resetItem(),
        ],
      ),
    );
  }

  /// 找回密码组件
  _resetItem() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        GestureDetector(
          onTap: _onTapFunZhmm,
          child: Text(
            "找回密码",
            style: FontUtil.fontBlue1(16),
          ),
        ),
      ],
    );
  }

  /// 找回密码方法
  _onTapFunZhmm() {
    String phone = _phoneController.text;
    Navigator.pushNamed(_context, "/resetPassword", arguments: {
      "phoneStr": phone,
    });
  }

  /// 登录按钮方法
  _loginButton() {
    return GestureDetector(
      onTap: () {
        _loginFun();
      },
      child: Container(
        // margin: EdgeInsets.symmetric(horizontal: 48),
        // height: 48,
        padding: EdgeInsets.symmetric(vertical: 8, horizontal: 100),
        decoration: BoxDecoration(
          color: colorBlue1,
          borderRadius: BorderRadius.all(Radius.circular(44)),
        ),
        child: Text(
          "登录",
          style: FontUtil.fontWhile1(18, fontWeight: FontWeight.w500),
        ),
      ),
    );
  }
  Widget _tourLoginButton() {
    return GestureDetector(
      onTap: () {
      //   还是让他选择考试科目
        Navigator.pushNamed(_context, "/select-exam");
      },
      child: Container(
        // margin: EdgeInsets.symmetric(horizontal: 48),
        // height: 48,
        padding: EdgeInsets.symmetric(vertical: 8, horizontal: 100),
        child: Text(
          "游客登录",
          style: FontUtil.fontBlue1(18, fontWeight: FontWeight.w500),
        ),
      ),
    );
  }

  /// 登录方法
  void _loginFun() async {
    // 判断是否同意协议
    if (!_isSelect) {
      // 未同意
      bool? agree = await ToastUtil.showDialogBox(
        context: _context,
        contentWidget: PhoneAgreementWidget(
          appConfig: widget.appConfig,
          dialogShow: true,
          fontSize: 28,
        ),
      );
      if (agree != null) {
        setState(() {
          _isSelect = !_isSelect;
        });
        _loginRequest();
      }
    } else {
      _loginRequest();
    }
  }

  /// 登录请求方法
  _loginRequest() {
    String captcha = ""; // 验证码
    String password = ""; // 密码
    LoginTypeEnum type; // 登录类型
    // 判断是否有手机号
    String phone = _phoneController.text;
    // if (!exp.hasMatch(phone)) {
    //   // 手机号有误
    //   ToastUtil.show(context: context, msg: "请输入正确的手机号");
    //   return;
    // }
    // 判断登录模式
    if (_inputIndex == 0) {
      // 验证码登录
      captcha = _captchaController.text;
      if (captcha.isEmpty) {
        ToastUtil.show(context: _context, msg: "请输入验证码");
        return;
      }
      type = LoginTypeEnum.phone;
    } else {
      // 密码登录
      password = _passwordController.text;
      if (password.isEmpty) {
        ToastUtil.show(context: _context, msg: "请输入密码");
        return;
      }
      type = LoginTypeEnum.username;
      // 密码不需要加密
    }
    if(loadingEntry==null){

    }else{
      loadingEntry!.remove();
    }
    // 开启加载框
    loadingEntry =   OverlayEntry(
      builder: (context) {
        return SpinKitThreeBounce(
          color: Colors.blue,
          size: 40.0,
        );
      },
    );
    //往Overlay中插入插入OverlayEntry
    Overlay.of(context).insert(loadingEntry!);
    // ToastUtil.loadingBoxShow(_context);
    // 发送密码
    LoginDao.login(
      userAccount: phone,
      type: type,
      code: captcha,
      credential: password,
    ).then((value) {
      loadingEntry!.remove();
      loadingEntry=null;
      if (mounted) {
        // 关闭加载框

        // ToastUtil.loadingBoxRemove();
        // 登录成功，判断返回方法
        if (widget.sucReturn == SucReturnEnum.ret) {
          // 携带成功参数返回
          Navigator.pop(context, true);
        } else if (widget.sucReturn == SucReturnEnum.toPage) {
          // 跳转对应页面
          Navigator.pushNamed(context, widget.pageName);
        } else {
          // 登录成功，跳转选择考试页面(不选择考试，则缓存没有考试相关信息，首页渲染错误)
          if (IndustryDao.isInitExamKey()) {
            Navigator.pushNamedAndRemoveUntil(
                context, "/tab", (route) => false);
          } else {
            Navigator.pushNamedAndRemoveUntil(
                context, "/select-exam", (route) => false);
          }
        }
      }
    }).catchError((e) {
      loadingEntry!.remove();
      loadingEntry=null;
      // 关闭加载框
      ToastUtil.loadingBoxRemove();
      // 登录失败
      String msg = "未知错误，请重试";
      if (e is DaoException) {
        msg = e.msg;
      }
      ToastUtil.show(context: _context, msg: msg);
    });
  }

  /// 游客登录方法
  _tourists() {
    if (widget.closeVisitors) {
      // NavigatorUtil.pushToHome(_context);
    } else {
      // NavigatorUtil.pop(_context);
    }
  }
}
